package com.agentframework.core.action;

import com.agentframework.core.exception.AgentException;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.converter.BeanOutputConverter;

import java.util.List;

/**
 * 结构化输出
 * @author wangjun
 **/
public abstract class BeanOutputAbstractAction extends AbstractAction {

    protected BeanOutputAbstractAction(String actionName) {
        super(actionName);
    }

    @Override
    public AssistantMessage execute(List<Message> messages) {
        AssistantMessage response = super.execute(messages);
        handleResponseMessage(response, getResponseType());
        return response;
    }

    protected abstract Class<?> getResponseType();

    protected void handleResponseMessage(Message message, Class<?> responseType) {
        try {
            Object convert = new BeanOutputConverter<>(responseType).convert(message.getText());
            doHandleResponseMessage(message, convert);
        } catch (Exception e) {
            getAgent().getContext().addErrorMessage(message);
            throw new AgentException(e);
        }
    }

    protected abstract void doHandleResponseMessage(Message message, Object response);

}
